package com.yjc.drygoods.member.interceptor;

import com.yjc.common.constant.AuthServerConstant;
import com.yjc.common.vo.MemberRespVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;

/**
 * @author yjc
 * @create 2022-09-23 20:47
 */
@Slf4j
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();
        String requestURI = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        HashSet<String> hashSet = new HashSet<>();
        hashSet.add("/member/member/regist");
        hashSet.add("/member/member/login");
        hashSet.add("/member/member/oauth2.0/weibo/login");
        hashSet.add("/member/membercollectsku/get/comnsume/attentionCount/relation");
        hashSet.add("/member/member/list");
        hashSet.add("/member/member/info");
        hashSet.add("/member/memberlevel/list");
        hashSet.add("/member/memberlevel/info");
        hashSet.add("/member/member/get/all/memberInfo");
        hashSet.add("/member/memberreceiveaddress/list");
        hashSet.add("/member/memberreceiveaddress/delete");
        hashSet.add("/member/memberreceiveaddress/info");
        hashSet.add("/member/memberreceiveaddress/save");
        hashSet.add("/member/memberreceiveaddress/update");
        hashSet.add("/member/membercollectsku/list");
        hashSet.add("/member/membercollectsku/delete");
        hashSet.add("/member/membercollectsku/info");
        hashSet.add("/member/membercollectsku/get/all/collect/skuInfo");
//        hashSet.add("/member/membercollectsku/save");
        hashSet.add("/member/membercollectsku/update");
        boolean match = hashSet.contains(requestURI);
        if (match) {
//            session.invalidate();
            return true;
        }

        MemberRespVo attribute = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        log.info("会员服务拦截器拦截会员信息：{}", attribute);
        if (attribute != null) {
            loginUser.set(attribute);
            return true;
        } else {
            session.setAttribute("msg", "请先登录");
            response.sendRedirect("http://auth.drygoods.top/login.html");
            response.setHeader("msg", "请先登录");
            return false;
        }
    }
}
